package org.gis.mvc.parser;

import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.gis.mapserver.base.ContextType;
import org.gis.mvc.bean.RequestBean;

/**
 *
 * @author gus
 */
public class RequestParser
{
    public final static String LONGITUDE = "longitude";
    public final static String LATITUDE = "latitude";
    public final static String ELEVATION = "elevation";
    public final static String SCALE = "scale";
    public final static String FORMAT = "context";
    public final static String LAYER_NAMES = "layers";

    public static RequestBean getRequestBean( HttpServletRequest request ) throws Exception
    {
        RequestBean bean = new RequestBean();

        bean.setLongitude(parseDouble((String) request.getParameter(LONGITUDE), 0));
        bean.setLatitude(parseDouble((String) request.getParameter(LATITUDE), 0));
        bean.setElevation(parseDouble((String) request.getParameter(ELEVATION), 0));
        bean.setScale(parseDouble((String) request.getParameter(SCALE), 0));
        
        bean.setContextType(parseContextType(request.getParameter(FORMAT)));
        bean.setLayerNames( parseLayers((String) request.getParameter(LAYER_NAMES)));
        return bean;
    }

    private static String [] parseLayers(String layers)
    {
        if(!layers.contains(","))
        {
            return new String[]{layers};
        }
        
        List<String> list = new LinkedList<String>();
        for(String layer : layers.split(","))
        {
            list.add(layer);
        }
        return list.toArray(new String[0]);
    }
    
    private static ContextType  parseContextType(String type) throws Exception
    {
        try
        {
            return ContextType.valueOf(type);
        }catch(Exception ex )
        {
            throw new Exception(String.format("cant create ContextType from ", type));
        }
    }
    
    private static double parseDouble( String value, double defaultValue )
    {
        double result = defaultValue;
        try
        {
            result = Double.parseDouble(value);
        } catch (Exception ex)
        {
        }
        return result;
    }
}
